<template>
  <PerfectTableComponent
    v-bind="$props"
    v-model:multipleSelection="multipleSelection"
    :loadTableList="loadTableList"
    :changePageSize="changePageSize"
    :changePage="changePage"
    :removeQueryField="removeQueryField"
    :clearQuery="clearQuery"
    v-model:query="query"
    title="车型配置"
    ref="tableRef"
    :queryFormHeaders="queryFormHeaders"
    :table="table"
    :tableColumns="tableColumns"
    :showTableIndex="false"
    :operatorColumnWidth="300"
    :baseUrl="urls.API_URL_BACKSTAGE_MES_CARMODELCONFIG"
    v-model:form="form"
    :formHeader="formHeader"
    formLabelWidth="120px"
    @beforeAddRow="beforeAddRow"
    @afterLoadDataSuccessInEditRow="afterLoadDataSuccessInEditRow"
    @beforeFormSubmit="beforeFormSubmit"
  >
    <!-----------------------------表格自定义列1----------------------------------------->
    <!--所属车型-->
    <template #table_column_carModelName="scope: any">
      {{ scope.row.carModel != null ? scope.row.carModel.name : '' }}
    </template>
  </PerfectTableComponent>
</template>

<script setup lang="ts">
import PerfectTableComponent from '@/components/base/table/PerfectTableComponent.vue';
import { onMounted, provide, reactive, ref } from 'vue';
import useTableList from '@/api/hooks/useTableList';
import type { FormHeader, ResponseData, TableColumn } from '@/types/interface/base_interface';
import urls from '@/api/request/urls';
import { getDict } from '@/api/dict';
import type { CarModel, CarModelConfig } from '@/types/interface/mes_interface';
import Request from '@/api/request/request';

// 表格工具必备参数
const { table, query, loadTableList, removeQueryField, clearQuery, changePageSize, changePage } = useTableList(
  urls.API_URL_BACKSTAGE_MES_CARMODELCONFIG
);
// 将表格刷新函数传到子容器
provide('loadTableList', loadTableList);

// 复选框选择的记录row集合，提供给父组件调用，例如在这个表格上用对话框再进行封装。
const multipleSelection = defineModel<any[]>('multipleSelection', {
  required: false,
  default: []
});
// 接收父组件（因为本组件供其他组件调用，因此封装）传递过来的值
interface Props {
  showToolBar?: Boolean; // 是否显示表格工具栏，默认显示
  showOperatorColumn?: Boolean; // 是否显示表格右侧的操作栏，默认显示
  showAddNewButton?: Boolean; // 在表格工具栏是否显示新增按钮
  showDeleteButton?: Boolean; // 是否显示删除按钮，如果不显示则整个表格插件都不显示
  showEditButton?: Boolean; //  是否显示编辑按钮，如果不显示则整个表格插件都不显示
  operatorColumnWidth?: number; // 表格右侧操作了大小
  dialogConfirmButtonText?: string; // 确认按钮上的文字
}
const props = withDefaults(defineProps<Props>(), {
  showToolBar: () => Boolean(true), //默认显示
  operatorColumnWidth: 300
});

//查询==========================================================
const queryFormHeaders = ref<FormHeader[]>([]);

//表格==========================================================
// 表格插件ref对象
const tableRef = ref();

//表格列
// 定义表格所有的列字段信息
const tableColumns = ref<TableColumn[]>([]);

//表单==========================================================
//表单对象
const form = ref<CarModelConfig>({});
//表单元素类型
const formHeader = ref<FormHeader[]>([]);

const getCarBrands = async () => {
  const resData: any = await new Request(urls.API_URL_BACKSTAGE_MES_CARBRAND + '/all').get();
  if (resData.success) {
    return resData.data;
  }
};
const getCarModels = async () => {
  const resData: any = await new Request(urls.API_URL_BACKSTAGE_MES_CARMODEL + '/all').get();
  if (resData.success) {
    return resData.data;
  }
};
onMounted(async () => {
  //获取汽车品牌列表
  const carBrands = await getCarBrands();
  //获取汽车车型列表
  const carModels = await getCarModels();
  //定义优先级选项。放在mounted中执行时，要将引用改变量的属性也放进来。
  const enabledDict = await getDict('启用状态', 'boolean');
  //汽车类型
  const carTypeDict = await getDict('汽车类型', 'string');
  //汽车能源类型
  const energyTypeDict = await getDict('汽车能源类型', 'string');
  //汽车类型
  const sizeTypeDict = await getDict('汽车大小类型', 'string');
  //汽车停产状态
  const carStopProductionDict = await getDict('汽车生产状态', 'boolean');
  queryFormHeaders.value = [
    // 查询表单
    {
      prop: 'name',
      label: '名称'
    },
    {
      prop: 'carBrandId',
      propAsName: 'carModel.carBrand.id',
      label: '汽车品牌',
      type: 'selectObject',
      list: carBrands,
      config: {
        valueKey: 'id',
        defaultProp: {
          value: 'id',
          label: 'name'
        }
      }
    },
    {
      prop: 'carModel.id',
      label: '车型',
      type: 'selectRemote',
      width: '200px',
      url: urls.API_URL_BACKSTAGE_MES_CARMODEL,
      queryNameForUrl: 'name',
      config: {
        valueKey: 'id',
        defaultProp: {
          value: 'id',
          label: '{name}'
        }
      }
    },
    {
      prop: 'stopProduction',
      label: '生产状态',
      type: 'select',
      list: carStopProductionDict
    },
    {
      prop: 'enabled',
      label: '是否启用',
      type: 'select',
      list: enabledDict
    }
  ];
  //表格对象
  tableColumns.value = [
    {
      label: '车型',
      prop: 'carModelName',
      type: 'custom',
      fixed: true,
      width: 150
    },
    {
      label: '名称',
      prop: 'name',
      fixed: true,
      width: 200
    },
    {
      label: '编码',
      prop: 'code',
      width: 150
    },
    {
      label: '生产状态',
      prop: 'stopProduction',
      width: 100,
      type: 'dict',
      dict: carStopProductionDict
    },
    {
      label: '启用状态',
      prop: 'enabled',
      width: 100,
      type: 'dict',
      dict: enabledDict,
      config: {
        dictTag: {
          primary: [true],
          danger: [false]
        }
      }
    },
    {
      label: '工艺数量',
      prop: 'technologyNumber',
      width: 100
    },
    {
      label: '创建时间',
      prop: 'createTime',
      width: 180
    },
    {
      label: '最后编辑时间',
      prop: 'updateTime',
      width: 180
    }
  ];
  // 添加编辑表单
  formHeader.value = [
    {
      prop: 'carModelId',
      label: '车型',
      type: 'selectRemote',
      action: 'post',
      width: '200px',
      url: urls.API_URL_BACKSTAGE_MES_CARMODEL,
      queryNameForUrl: 'name',
      config: {
        valueKey: 'id',
        defaultProp: {
          value: 'id',
          label: '{name}'
        }
      },
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      prop: 'carModelName',
      label: '车型',
      action: 'put',
      disabled: true
    },
    {
      label: '名称',
      prop: 'name',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        },
        {
          min: 1,
          max: 50,
          message: '长度在 1 到 50个字符',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '编码',
      prop: 'code',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        },
        {
          min: 1,
          max: 50,
          message: '长度在 1 到 50个字符',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '生产状态',
      prop: 'stopProduction',
      type: 'select',
      list: carStopProductionDict,
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    // {
    //   label: '是否启用',
    //   prop: 'enabled',
    //   type: 'switch',
    //   list: enabledDict,
    //   rules: [
    //     {
    //       required: true,
    //       message: '不能为空',
    //       trigger: 'blur'
    //     }
    //   ]
    // },
    {
      label: '描述',
      prop: 'description',
      type: 'textarea',
      rules: [
        {
          max: 255,
          message: '长度不能超过255个字符',
          trigger: 'blur'
        }
      ]
    }
  ];
});
//在添加行的动作以前
const beforeAddRow = async () => {
  //传入初始值
  form.value = {
    stopProduction: false,
    enabled: true
  };
};
//在编辑行读取后端记录后需要修改的地方
const afterLoadDataSuccessInEditRow = async (formEdit: CarModelConfig) => {
  //重新封装表单对象的值
  if (formEdit.carModel != null) {
    formEdit.carModelName = formEdit.carModel.name;
  }
};
//在表单提交前对对象进行封装
const beforeFormSubmit = () => {
  if (form.value.carModelId != null) {
    form.value.carModel = {
      id: form.value.carModelId
    };
  }
};

//清空表格选中的复选框
const clearSelection = () => tableRef.value!.clearSelection();
defineExpose({
  clearSelection,
  clearQuery,
  loadTableList
});
</script>

<style scoped></style>
